﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Singleton;
using IntroduceCompany.Util;
using System.IO;

namespace IntroduceCompany.Controllers
{
    [HandleError]
    [IntroduceCompany.Models.CheckModule(ConstantClass.Backend_Product_MenuID)]
    public class ProductController : BaseController
    {
        // GET: /Product/

        #region ProductBackend


        /// <summary>
        /// View All Product on 
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ProductListBackend()
        {
            if (DataSingleton.GetMenuListModels().AccepGoToFunctionManage(1, "Product", "ProductListBackend"))
            {

                //Check Cookie Language
                string languageID = ConstantClass.markViewAllLanguage;
                if (Request.Cookies[ConstantClass.cooLanguage] != null && Request.Cookies[ConstantClass.cooLanguage].Value != "")
                {
                    languageID = Request.Cookies[ConstantClass.cooLanguage].Value;
                }


                string productTypeID = "0";
                if (Request.Cookies[ConstantClass.cooProductType] != null)
                {
                    //HttpCookie cookie = new HttpCookie(ConstantClass.cooProductType, productTypeID);
                    //cookie.Expires = DateTime.Now.AddHours(-1);
                    //Response.Cookies.Add(cookie);
                    productTypeID = Request.Cookies[ConstantClass.cooProductType].Value;
                }

                ViewData["ProductTypeList"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeList(), "MenuListID", "MenuName", productTypeID);
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", languageID);

                return View("/Views/Backend/Product/ProductList.aspx", DataSingleton.GetProductModels().GetAllProductList(languageID, productTypeID));
            }
            else
            {
                return Redirect(ConstantClass._LoginError);
            }
        }


        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ProductEdit(String productID, String productLanguageID)
        {
            
            ViewData["DDLProductType"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeListForEdit(productLanguageID), "MenuListID", "MenuName");
            ViewData["DDLProductStatus"] = new SelectList(DataSingleton.GetProductModels().GetProductStatusList(productLanguageID), "ProductStatusID", "ProductStatusName");
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", productLanguageID);
            
            ProductListView oneProductView = DataSingleton.GetProductModels().GetProductDetails(productID, productLanguageID);

            //Geting information in product table when Product language of this product is not exist.
            if (oneProductView == null)
            {
                oneProductView = new ProductListView();
                Product product = DataSingleton.GetProductModels().GetProductByProductID(productID);

                oneProductView.ProductID = product.ProductID;
                oneProductView.ProductPrice = product.ProductPrice;
                oneProductView.CreateDate = product.CreateDate;
                oneProductView.UpdateDate = product.UpdateDate;
                oneProductView.ViewNumber = product.ViewNumber;
                oneProductView.FullName = product.Administrator.FullName;
            }

            return View("/Views/Backend/Product/ProductEdit.aspx", oneProductView);
        }


        [Authorize(Roles = ConstantClass.autProduct)]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ProductEditSubmit(ProductListView productListView, HttpPostedFileBase uploadFile)
        {
            string username = HttpContext.User.Identity.Name;

            //Edit information of product when press Save button. Not Edit when change language
            if (DataSingleton.GetProductModels().CheckProductLanguageIsExisted(productListView.ProductID, productListView.ProductLanguageID)  )
            {
                //foreach (var modelStateValue in ViewData.ModelState.Values)
                //{
                //    foreach (var error in modelStateValue.Errors)
                //    {
                //        // Do something useful with these properties
                //        var errorMessage = error.ErrorMessage;
                //        var exception = error.Exception;
                //    }
                //}

                //Edit product
                if (ModelState.IsValid && DataSingleton.GetProductModels().UpdateProduct(productListView, username))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Thông tin sản phẩm đã được cập nhật.");
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thông tin sản phẩm.");
                }
                ViewData["DDLProductType"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeListForEdit(productListView.ProductLanguageID), "MenuListID", "MenuName");
                ViewData["DDLProductStatus"] = new SelectList(DataSingleton.GetProductModels().GetProductStatusList(productListView.ProductLanguageID), "ProductStatusID", "ProductStatusName");
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", productListView.ProductLanguageID);

                return View("/Views/Backend/Product/ProductEdit.aspx", DataSingleton.GetProductModels().GetProductDetails(productListView.ProductID, productListView.ProductLanguageID));
            }
            else
            {
                //Insert another language for product

                ViewData["DDLProductType"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeListForEdit(productListView.ProductLanguageID), "MenuListID", "MenuName");
                ViewData["DDLProductStatus"] = new SelectList(DataSingleton.GetProductModels().GetProductStatusList(productListView.ProductLanguageID), "ProductStatusID", "ProductStatusName");
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", productListView.ProductLanguageID);

                if (ModelState.IsValid && TryUpdateModel(productListView) && DataSingleton.GetProductModels().InsertProductLanguage(productListView))
                {
                    ModelState.Clear();
                    ModelState.AddModelError("NoticePage", "Thông tin sản phẩm đã được cập nhật thêm ngôn ngữ mới.");

                    return View("/Views/Backend/Product/ProductEdit.aspx", DataSingleton.GetProductModels().GetProductDetails(productListView.ProductID, productListView.ProductLanguageID));
                }
                else
                {
                    ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thêm ngôn mới cho sản phẩm.");

                    return View("/Views/Backend/Product/ProductEdit.aspx", productListView);
                }
            }
 
        }


        /// <summary>
        /// Event When Changing Product Type
        /// </summary>
        /// <param name="productTypeID"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ChangeProductType(String productTypeID)
        {

            if (Request.Cookies[ConstantClass.cooProductType] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooProductType, productTypeID);
                cookie.Expires = DateTime.Now.AddHours(2);
                Response.Cookies.Add(cookie);
            }
            else
            {
                Response.Cookies[ConstantClass.cooProductType].Value = productTypeID;
            }

            return RedirectToAction("ProductListBackend", "Product");
        }


        /// <summary>
        /// Delete a product
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ProductDelete(String productID)
        {

            DataSingleton.GetProductModels().DeleteProduct(productID, (Request.PhysicalApplicationPath.ToString() + "Image/Product/"));
            return RedirectToAction("ProductListBackend", "Product");
        }


        /// <summary>
        /// Change Product state that is visible or invisible
        /// </summary>
        /// <param name="menuListID"></para
        /// <param name="menuVisible"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ChangeProductVisible(String productID, bool productVisible)
        {
            DataSingleton.GetProductModels().ChangeProductVisible(productID, productVisible);
            return RedirectToAction("ProductListBackend", "Product");
        }



        /// <summary>
        /// Go to Product Create Views
        /// </summary>
        /// <param name="languageID"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ProductCreate()
        {

            ViewData["DDLProductType"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeListForEdit(ConstantClass.mainLanguageID), "MenuListID", "MenuName");
            ViewData["DDLProductStatus"] = new SelectList(DataSingleton.GetProductModels().GetProductStatusList(ConstantClass.mainLanguageID), "ProductStatusID", "ProductStatusName");
            ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", ConstantClass.mainLanguageID);

            return View("/Views/Backend/Product/ProductCreate.aspx");
        }


        [Authorize(Roles = ConstantClass.autProduct)]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ProductCreate(ProductListView productListView)
        {
            string username = HttpContext.User.Identity.Name;
            bool checkInsert = false;

            if (ModelState.IsValid)
            {
                if (TryUpdateModel(productListView))
                {
                    if (!DataSingleton.GetProductModels().IsDuplicateProductID(productListView.ProductID))
                    {
                        checkInsert = DataSingleton.GetProductModels().CreateProduct(productListView, username);
                    }
                    else
                    {
                        ModelState.AddModelError("NoticePage", "Mã sản phẩm này đã tồn tại. Xin vui lòng đổi mã khác.");
                    }
                }
            }

            if (checkInsert) // Go to Product Edit after insert successful to insert other language
            {
                ViewData["DDLProductType"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeListForEdit(productListView.ProductLanguageID), "MenuListID", "MenuName");
                ViewData["DDLProductStatus"] = new SelectList(DataSingleton.GetProductModels().GetProductStatusList(productListView.ProductLanguageID), "ProductStatusID", "ProductStatusName");
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", productListView.ProductLanguageID);

                return RedirectToAction("ProductEdit", "Product", new { productID = productListView.ProductID, productLanguageID = productListView.ProductLanguageID });
            }
            else  // Return Product Create if there are any error.
            {

                ViewData["DDLProductType"] = new SelectList(DataSingleton.GetProductModels().GetProductTypeListForEdit(ConstantClass.mainLanguageID), "MenuListID", "MenuName");
                ViewData["DDLProductStatus"] = new SelectList(DataSingleton.GetProductModels().GetProductStatusList(ConstantClass.mainLanguageID), "ProductStatusID", "ProductStatusName");
                ViewData["LaguageList"] = new SelectList(DataSingleton.GetLanguageModels().GetLanguageList().ToList(), "LanguageID", "LanguageName", ConstantClass.mainLanguageID);

                return View("/Views/Backend/Product/ProductCreate.aspx", productListView);
            }
        }


        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult ProductImageList(String productID)
        {
            ViewData["productID"] = productID;
            return View("/Views/Backend/Product/ProductImage.aspx", DataSingleton.GetProductModels().GetProductImages(productID));
        }


        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult InsertProductImage(String productID, IEnumerable<HttpPostedFileBase> fileToUpload)
        {
            DataSingleton.GetProductModels().UploadProductImage(productID, fileToUpload, Path.Combine(Request.PhysicalApplicationPath.ToString(), "Image/Product/"));
            return RedirectToAction("ProductImageList", "Product", new { productID = productID });
        }


        [Authorize(Roles = ConstantClass.autProduct)]
        public ActionResult DeleteProductImage(int imageID, String productID)
        {
            DataSingleton.GetProductModels().ProductImageDelete(imageID, Path.Combine(Request.PhysicalApplicationPath.ToString(), "Image/Product/"));
            return RedirectToAction("ProductImageList", "Product", new { productID = productID });
        }


        #endregion



        #region ProductFrontend


        public ActionResult ProductListFrontend()
        {
            //Remember current url into cookie for link Continue buy product in cart page
            String oldUrl = ControllerContext.HttpContext.Request.RawUrl;
            if (Request.Cookies[ConstantClass.cooUrlContinueBuyProduct] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooUrlContinueBuyProduct, oldUrl);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
            }
            else
            {
                Response.Cookies[ConstantClass.cooUrlContinueBuyProduct].Value = oldUrl;
            }

            return View("/Views/Frontend/Product/Product.aspx");
        }


        public ActionResult ProductDetails(String productSeo_URL)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();
            string productID = DataSingleton.GetProductModels().GetProductIDByProductSeoUrl(productSeo_URL);

            if (productID != null)
            {
                ViewData["ProductImages"] = DataSingleton.GetProductModels().GetProductImages(productID);
                DataSingleton.GetProductModels().UpdateViewNumberOfProduct(productID);

                return View("/Views/Frontend/Product/ProductDetails.aspx", DataSingleton.GetProductModels().GetProductDetails_Frontend(productID, languageID));
            }
            else
            {
                return View("/Views/Frontend/Product/ProductDetails.aspx", null);
            }
        }

        /// <summary>
        /// use in backend , productList but link to frontend for admin to check quickly
        /// </summary>
        /// <param name="articleSEO_URL"></param>
        /// <returns></returns>
        public ActionResult ProductDetails2(String productID, String languageID, int productTypeID)
        {
            string url = "/" + languageID + "/prDe/";
            string productType_SEO_URL = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(productTypeID.ToString(), languageID);
            string product_SEO_URL = DataSingleton.GetProductModels().GetProductSeoUrl_By_ProductID_LanguageID(productID, languageID);
            url += productType_SEO_URL + "/" + product_SEO_URL;
            return Redirect(url);
        }


        [ChildActionOnly]
        public ActionResult GetNewProductList()
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();

            //Getting 5 new product
            ViewData["NewProductList"] = DataSingleton.GetProductModels().GetNewProductList(6, languageID);

            //Getting 5 product have biggest view number
            ViewData["BiggestViewNumberProductList"] = DataSingleton.GetProductModels().GetBiggestViewNumberProductList(6, languageID);

            return View("/Views/Frontend/Product/Middle.ascx");
        }


        public ActionResult ProductList(String productTypeSEO_URL, String pageIndex)
        {

            //Remember current url into cookie for link Continue buy product in cart page
            String oldUrl = ControllerContext.HttpContext.Request.RawUrl;
            if (Request.Cookies[ConstantClass.cooUrlContinueBuyProduct] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooUrlContinueBuyProduct, oldUrl);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
            }
            else
            {
                Response.Cookies[ConstantClass.cooUrlContinueBuyProduct].Value = oldUrl;
            }

            ViewData["productTypeSEO_URL"] = productTypeSEO_URL;
            ViewData["pageIndex"] = pageIndex;// để truyền pageIndex("1","2","3",...) dến Func MiddleProductList.ascx(partial view) thông wa trang ProductList.aspx
            return View("/Views/Frontend/Product/ProductList.aspx");
        }


        [ChildActionOnly]
        public ActionResult ProductListByType(String productTypeSEO_URL, String pageIndex)
        {
            //Check Cookie Language
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();

            int menuListID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(productTypeSEO_URL);

            if (menuListID != 0)
            {
                ////////////////////////// start paging
                int totalRows = DataSingleton.GetProductModels().Frontend_GetTotalRowsOneProductTypeOneLanguage(menuListID, languageID);
                int totalPages = (int)Math.Ceiling((double)totalRows / (double)ConstantClass.ProductPageStep);

                if (pageIndex != "1")
                {
                    ViewData["Previous_Mark_Visibility"] = "true";
                }
                if (totalPages != Convert.ToInt16(pageIndex))
                {
                    ViewData["Next_Mark_Visibility"] = "true";
                }

                ViewData["NextPageIndex"] = (Convert.ToInt16(pageIndex) + 1).ToString();
                ViewData["PreviousPageIndex"] = (Convert.ToInt16(pageIndex) - 1).ToString();
                ////////////////////////// end paging

                ViewData["ProductListByType"] = DataSingleton.GetProductModels().GetOnePageProductListByType(menuListID, languageID, pageIndex, ConstantClass.ProductPageStep);
                ViewData["ProductTypeName"] = DataSingleton.GetMenuListModels().GetMenuTypeName(menuListID, languageID);

                return View("/Views/Frontend/Product/MiddleProductList.ascx");
            }
            else
            {
                ViewData["ProductListByType"] = null;
                return View("/Views/Frontend/Product/MiddleProductList.ascx");
            }
        }


        /// <summary>
        /// Get a product image name in product images
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        public String GetOneProductImage(String productID)
        {
            IQueryable<ProductImage> tempProductImageList = DataSingleton.GetInstance().ProductImages.Where(img => img.ProductID == productID)
                .OrderBy(img => img.ProductImageID);

            string productImage = tempProductImageList.Count() == 0 ? "" : tempProductImageList.First().ProductImageName;

            return (productImage);
        }




        #endregion


    }
}
